<template>
  <!-- v-model="open" -->
  <el-dialog :visible.sync="open" width="50%">
    <div slot="header" class="header-bar">
      <Icon type="md-pin" size="18" />
      <b>{{ deviceName }}——设备详情</b>
    </div>
    <div slot="footer"></div>
    <el-button slot="close" type="error" size="small" icon="md-close"></el-button>

    <el-tabs v-model="activeTab" type="card" :animated="true">
      <el-tab-pane name="params" label="设备属性">
        <el-form :label-width="82" ref="form">
          <el-row :gutter="24">
            <el-col v-for="(param, index) in paramsData" :span="param.columnSpan * 12" :key="index">
            <el-form-item :label="param.comments">
              <el-input v-if="param.type === '多行编辑框'" type="textarea" :value="param.value" :rows="4" readonly></el-input>
              <el-input v-else :value="param.value" readonly></el-input>
            </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span v-if="!paramsData.length" size="large" fix>数据加载中...</span>
      </el-tab-pane>
      <el-tab-pane name="current" label="实时数据">
        <el-table border :columns="columns" :data="currentData" :height="tableHeight" :loading="tableLoading"></el-table>
      </el-tab-pane>
      <el-tab-pane name="constrol" label="控制">
        <div class="control" :style="{ height: tableHeight + 'px' }">
          <el-row v-for="(entry, index) in controlData" :gutter="16" :key="index">
            <el-col span="8">{{ entry.descrs }}（{{ entry.code }}）</el-col>
            <el-col span="8">
            <el-button type="default" size="small" :loading="controlLoading"
              :disabled="!entry.pre_set || entry.r_value === entry.rt_val" long
              @click="handleControl(1, entry)">预置</el-button>
            </el-col>
            <el-col span="8">
            <el-button type="info" size="small" :loading="controlLoading" :disabled="entry.r_value === entry.rt_val" long
              @click="handleControl(2, entry)">{{ entry.name }}</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-input type="textarea" :value="controlText" readonly></el-input>
          </el-row>
        </div>
      </el-tab-pane>
      <el-tab-pane name="histroy" label="历史曲线">
        <div class="history" :style="{ height: tableHeight + 'px' }">
          <div class="filter">
            <div class="item">
              <label>起始时间：</label>
              <DatePicker v-model="startDate" type="date" style="width: 110px" :clearable="false" :options="startOption">
              </DatePicker>
            </div>
            <div class="item">
              <Checkbox v-model="hasEndDate">终止时间：</Checkbox>
              <DatePicker v-model="endDate" type="date" style="width: 110px" :clearable="false" :options="endOption"
                :disabled="!hasEndDate"></DatePicker>
            </div>
            <div class="item">
              <Select :value="1" style="width: 100px" disabled>
                <Option :value="1">实际采样</Option>
              </Select>
            </div>
            <div class="item">
              <Button type="info" @click="getHistroyData">显示曲线</Button>
            </div>
          </div>
          <div class="panel">
            <div class="param" :style="{ width: paramWidth + 'px' }">
              <Scroll>
                <Tree :data="stdTree" :render="renderTree" show-checkbox ref="tree"></Tree>
              </Scroll>
              <div class="toggle-button" @click="toggleParamTree">
                <Icon :type="toggleIcon"></Icon>
              </div>
            </div>
            <div class="chart">
              <div class="chart-panel" ref="chart"></div>
            </div>
            <Spin v-if="!stdTree[0].children.length" size="large" fix></Spin>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>
<script>
import Chart from './chart';
import Ajax from '../ajax';
import fecha from '@/utils/date';
import { getStyle } from '@/utils/assist';
export default {
  name: 'CustomModal',
  data() {
    return {
      deviceName: '',
      open: false,
      activeTab: 'current',
      oid: 0,
      paramsData: [],

      tableLoading: true,
      tableHeight: 410,
      columns: [
        {
          title: '序号',
          width: 70,
          type: 'index',
          align: 'center',
          className: 'index-color'
        },
        {
          title: '名称',
          key: 'pointName'
        },
        {
          title: '编码',
          key: 'pointId'
        },
        {
          title: '当前状态',
          width: 200,
          align: 'center',
          render(h, params) {
            return h('b', parseFloat(params.row.val));
          }
        },
        {
          title: '单位',
          key: 'unit',
          width: 100
        }
      ],
      currentData: [],

      controlLoading: false,
      controlData: [],
      controlText: '',

      paramWidth: 170,
      toggleIcon: 'ios-arrow-back',
      startDate: new Date(),
      endDate: '',
      hasEndDate: false,
      startOption: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        }
      },
      stdTree: [
        {
          title: '',
          deep: 1,
          expand: true,
          children: []
        }
      ]
    };
  },
  computed: {
    endOption() {
      const minDate = this.startDate.valueOf();
      return {
        disabledDate(date) {
          return date && (date.valueOf() > Date.now() || date.valueOf() < minDate);
        }
      };
    }
  },
  watch: {
    deviceName(val) {
      this.stdTree[0].title = val;
      Chart.initChart(this.$refs.chart, [], {
        suffixTitle: '采样历史曲线',
        devName: this.deviceName,
        startDate: this.startDate,
        endDate: this.endDate
      });
    },
    hasEndDate(val) {
      if (val) {
        this.endDate = this.startDate;
      } else {
        this.endDate = '';
      }
    }
  },
  methods: {
    setOid(id) {
      this.oid = id;
      this.deviceName = '数据加载中';
      // this.activeTab = 'current';
      this.tableLoading = true;
      this.open = true;
      this.paramsData = [];
      this.controlText = '';
      this.controlData = [];
      this.currentData = [];
      this.stdTree[0].children = [];
      this.getParamsData();
      this.getCurrentData();
      this.getControlData();
      this.getStdcodeData();
    },
    async getParamsData() {
      const reqData = await Ajax.GetDeviceData({ oid: this.oid });
      // 接口没有code msg封装
      this.paramsData = reqData;
      // 取设备名称
      if (reqData.length) {
        this.deviceName = reqData[0].value;
      }
      this.calculateHeight();
    },
    async getCurrentData() {
      const reqData = await Ajax.GetDeviceRes({ oid: this.oid });
      if (reqData.length && reqData[0].points) {
        this.currentData = reqData[0].points;
      }
      this.tableLoading = false;
    },
    async getStdcodeData() {
      const reqData = await Ajax.GetResStdcod({ oid: this.oid });
      for (let key in reqData) {
        const stdItem = {
          title: key,
          deep: 2,
          expand: true,
          checked: false,
          children: []
        };
        reqData[key].forEach(entry => {
          stdItem.children.push({
            title: entry.name,
            code: entry.code,
            type: entry.viewType,
            checked: false
          });
        });
        this.stdTree[0].children.push(stdItem);
        this.triggerResize();
      }
    },
    async getControlData() {
      const reqData = await Ajax.GetControlStatus({
        devId: this.oid
      });
      if (reqData.code && reqData.msg.length) {
        this.controlData = reqData.msg;
        if (this.controlText) {
          this.controlText += '\n';
        }
        this.controlText += fecha.format(Date.now(), 'yyyy-MM-dd HH:mm:ss.SSS') + '--> 获取当前控制状态成功！';
      } else {
        this.controlText = '没有控制信息！';
      }
      this.controlLoading = false;
    },
    async getHistroyData() {
      const checkedStd = this.$refs.tree.getCheckedNodes();
      if (checkedStd.length) {
        let stdCodes = '';
        checkedStd.forEach(entry => {
          if (entry.code) {
            if (stdCodes) {
              stdCodes += ',' + entry.code;
            } else {
              stdCodes = entry.code;
            }
          }
        });
        const reqData = await Ajax.GetResHistory({
          oid: this.oid,
          stdcodes: stdCodes,
          startTime: fecha.format(this.startDate, 'yyyyMMdd'),
          endTime: this.endDate ? fecha.format(this.endDate, 'yyyyMMdd') : fecha.format(this.startDate, 'yyyyMMdd')
        });
        Chart.initChart(this.$refs.chart, reqData, {
          suffixTitle: '采样历史曲线',
          devName: this.deviceName,
          startDate: this.startDate,
          endDate: this.endDate
        });
      } else {
        this.$Message.warning('请至少选择一个参数！');
      }
    },
    renderTree(h, { root, node, data }) {
      let icon = 'ios-list-outline';
      if (data.deep === 1) {
        icon = 'ios-home';
      } else if (data.deep === 2) {
        icon = 'ios-speedometer-outline';
      }
      const nTree = this.$refs.tree;
      return h('span', {
        class: 'tree-node',
        attrs: {
          title: data.title + (data.code ? (',' + data.code) : '')
        },
        on: {
          click() {
            nTree.handleCheck({
              checked: !data.checked,
              nodeKey: node.nodeKey
            });
          }
        }
      }, [
        h('Icon', {
          props: {
            type: icon
          }
        }),
        h('span', {
          class: 'node-title'
        }, data.title)
      ]);
    },
    toggleParamTree() {
      if (this.paramWidth > 0) {
        this.paramWidth = 0;
        this.toggleIcon = 'ios-arrow-forward';
      } else {
        this.paramWidth = 170;
        this.toggleIcon = 'ios-arrow-back';
      }
      setTimeout(() => {
        this.resizeChart();
      }, 500);
    },
    async handleControl(cmd, item) {
      this.controlLoading = true;
      // item.control_type;控制类型(0遥控,1遥调)
      this.controlText += '\n' + fecha.format(Date.now(), 'yyyy-MM-dd HH:mm:ss.SSS') + '--> 控制命令已发送！';
      const reqData = await Ajax.SendControlConmand({
        cmdType: cmd,
        resourceId: item.resource_id,
        resourceName: this.deviceName,
        ykId: item.id
      });
      this.controlText += '\n' + fecha.format(Date.now(), 'yyyy-MM-dd HH:mm:ss.SSS') + '--> ' + reqData.msg + '！';
      if (cmd === 2) {
        setTimeout(() => {
          this.getControlData();
        }, 500);
      } else {
        this.controlLoading = false;
      }
    },
    triggerResize() {
      let e = document.createEvent('Events');
      e.initEvent('resize', true, true);
      setTimeout(() => {
        document.dispatchEvent(e);
      }, 400);
    },
    calculateHeight() {
      setTimeout(() => {
        const firstHeight = parseFloat(getStyle(this.$refs.form.$el, 'height'));
        if (firstHeight && firstHeight > 300) {
          this.tableHeight = firstHeight;
        }
      }, 100);
    },
    resizeChart() {
      Chart.resizeChart();
    }
  },
  mounted() {
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    Chart.disposeChart();
    window.removeEventListener('resize', this.resizeChart);
  }
};
</script>
